package Persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * This class is able to open a connection with the database and execute queries on it.
 * 
 * @author kenneth
 */
public class DatabaseConnection {
    
    private static final String URL = "jdbc:mysql://kennero87.eightyseven.axc.nl:3306/";
    private static final String DB_NAME = "kennero87_datacom";
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String USERNAME = "kennero87_user";
    private static final String PASSWORD = "datacomproject";
    
    private Connection connection;
    
    /**
     * Opens the connection with the database
     */
    public void openConnection() {
        try {
          Class.forName(DRIVER).newInstance();
          connection = DriverManager.getConnection(URL+DB_NAME,USERNAME,PASSWORD);          
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * Executes a select query on the database
     *
     * @param query The query that needs to be executed
     * @return The resultSet
     * @throws SQLException If a database error occurs
     */
    public ResultSet executeQuery(String query) throws SQLException {
        Statement statement = connection.createStatement();
        return statement.executeQuery(query);
    }
    
    /**
     * Executes an update query on the database
     *
     * @param query The query that needs to be executed
     * @return Returns nothing
     * @throws SQLException If a database error occurs
     */
    public int executeUpdate(String query) throws SQLException {
        Statement statement = connection.createStatement();
        return statement.executeUpdate(query);
    }
    
    /**
     * Closes the connection with the database
     */
    public void closeConnection() {
        try {
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
